from . import app_weixin_pay
from conn_mysql import ConnectMysql
from .setting import config
from flask import request, render_template, session, flash,redirect
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from weixin import Weixin, WeixinError



weixin = Weixin(config)


@app_weixin_pay.route("/jsapi")
def pay_jsapi():
    """微信网页支付请求发起"""
    openid = session.get("openid")
    body = '全网教育平台会员'
    total_fee = 1
    
    if not all((openid, body, total_fee)):

        flash('微信环境下浏览本页', 'alert-success')

        return redirect('/openid_callback')
        
        

    try:

        out_trade_no = weixin.nonce_str
        raw = weixin.jsapi(openid=openid, body=body, out_trade_no=out_trade_no, total_fee=total_fee)
        # print(raw)#{'package': 'prepay_id=wx131649165306681b1592d03b1839799800', 'appId': 'wx90014a2b7a9ab7f2', 'signType': 'MD5', 'timeStamp': '1586767756', 'nonceStr': 'vBNkDYLmodxPeCVNDz0SAbkyIqXoSK4A', 'sign': '3F950C1AD3FBE2F9551E92BDA406473C'}
        #定单入库
        # conn_obj = ConnectMysql()#链接数据库
        # sql = 'insert into prepay(prepay_id, openid, body, total_fee) values (%s,%s,%s,%s)'
        # conn_obj.insert_info(
        #     sql, 
        #     (raw['package'].replace('prepay_id=', ''), openid, body, total_fee)
        # )
        # conn_obj.close()

        return render_template('pay.html', raw = raw)


    except WeixinError as e:
        
        return {
                'status': -1,
                'errorCode': '1003',
                'errorMsg': e.args[0],
                'resultBody': None
            }


@app_weixin_pay.route("/notify", methods = ['POST', "GET"])
def pay_notify():
    """
    微信异步通知
    """


    data = weixin.to_dict(request.data)

    print(data)
    with open('pay_notify.log', 'a') as f:
        f.write('\n')
        f.write(str(data))
        f.write('\n')
    
    
   
    if not weixin.check(data):#签名验证失败
        return weixin.reply("签名验证失败", False)
    
    openid = data.get('openid')
    print(f"回调openid{openid}")
    return_code = data.get('return_code')
    result_code = data.get('result_code')

    if result_code == 'SUCCESS' and return_code == 'SUCCESS': #付费成功

        with ConnectMysql() as c:

            sql = "UPDATE openid SET pay=1 WHERE openid=%s"

            c.update_info(sql, (openid,))

        return weixin.reply("OK", True)

    else:
        return weixin.reply("签名验证失败", False)
